#_*_ coding: UTF-8 _*_
import  os
from DataCleaning import  DataCleaning
class ConnectTrack:
    '''
    拼接轨迹
    '''
    # def  __init__(self,trackFile,x,y,width,height,threshold):
    def __init__(self, trackFile,idMap):
        '''
        初始化函数
        :param trackFile:（DataFrame）储存单个摄像头顾客轨迹的DataFrame
        :param ipMap:(dict)单个摄像头下的ID映射关系
        '''
        self.trackFile=trackFile
        # self.realId=realId
        self.idMap=idMap
        # self.x=x
        # self.y=y
        # self.width=width
        # self.height=height
        # self.threshold=threshold

    def setTrackFile(self,trackFile):
        self.trackFile=trackFile

    def setIdMap(self,idMap):
        self.idMap=idMap


    def connect(self,consumerID):
        '''
        拼接潜在用户的轨迹
        :param consumerID:（string）潜在用户最后的id值
        :return:（list）拼接列表
        '''

        connectList = []
        firstCon=self.trackFile[self.trackFile.tmp_id==float(consumerID)]
        lines=firstCon.values[0]
        if len(lines)!=7:
            print "数据有残缺---ConnectTrack1"
        sFrame=lines[0]
        sX,sY,sWidth,sHeight=lines[2:6] #id为consumerId的顾客轨迹开始的帧数及坐标
        connectList.append(consumerID)

        tag=True

        while tag:
            minFrame=10000.0
            minDistance=10000.0

            minFrameDistance = ""#在帧数最小的情况下的距离值
            minFrameCon = ""#帧数最小的顾客ID
            minDistanceFrame = ""#记录最小情况下的帧数差
            minDistanceCon = ""#距离最小的顾客ID

            for i, group in self.trackFile.groupby('tmp_id'):
                i=str(i)

                if float(i)>=float(connectList[-1]) :#倒着拼接
                    continue
                if  float(connectList[-1])-float(i) > 100:
                    break
                if i in connectList:#已经拼接过得不在重复拼接
                    continue

                secondCon=group.values[-1]
                if len(secondCon)!=7:
                    print "数据有残缺---ConnectTrack2"

                eFrame=secondCon[0]
                eX, eY, eWidth, eHeight = secondCon[2:6]  # id为tmpID的顾客轨迹开始的帧数及坐标
                dFrame=float(sFrame)-float(eFrame)
                dDistance=DataCleaning(" ").euclideanDistances(sX,sY,eX,eY)

                if dFrame < minFrame  and  float(sFrame) > float(eFrame) and dFrame > 4:  # 记录帧数之差与需要拼接的顾客最小的被拼接顾客的信息,dFrame>1:Dframe不能等于0，即丢失时同时出现
                    minFrame = dFrame
                    minFrameDistance = dDistance
                    minFrameCon = i
                if dDistance < minDistance and float(sFrame) > float(eFrame):  # 记录距离之差与需要拼接的顾客最小的被拼接顾客的信息
                    minDistance = dDistance
                    minDistanceFrame = dFrame
                    minDistanceCon =i

            if  minDistanceCon==minFrameCon:
                if minFrameCon == "":  # 拼接到了1.txt,即拼接到了最开始
                    break
                if minFrameCon not in connectList:
                    connectList.append(minFrameCon)
                    # if l==len(connectList):
                    #     tag=False
                    # print minFrameCon
                    # print tag
            else:
                if minDistanceCon == ""  and  minFrameCon!="" :
                    if minFrameCon not in connectList:
                        connectList.append(minFrameCon)


                elif minDistanceCon != ""  and  minFrameCon==""  :
                    if minDistanceCon not in connectList:
                        connectList.append(minDistanceCon)


                elif minDistanceCon != ""  and  minFrameCon!="":
                    if float(minFrame)/100.0+float(minFrameDistance)>=float(minDistance)+float(minDistanceFrame)/100.0:
                    # if  minFrameDistance > minDistance :

                        if minDistanceCon not in connectList:
                            connectList.append(minDistanceCon)
                        # if l == len(connectList):
                        #     tag = False
                        # print minDistanceCon
                    else:
                        if minFrameCon not in connectList:
                            connectList.append(minFrameCon)
                else:
                    break

            lastConLine=self.trackFile[self.trackFile.tmp_id==float(connectList[-1])].values[0]

            if len(lastConLine) != 7:
                print "数据有残缺---ConnectTrack3"

                # if SimilarTrack().euclideanDistances(lastConLine[2],lastConLine[3],self.x,self.y)/float(eWidth)<=float(self.threshold):
            if self.idMap[connectList[-1]] != "":  # “”是没有人脸id时的补位
                tag = False  # 拼接到的临时id有对应的真实id时，停止拼接
            else:
                sFrame = lastConLine[0]
                sX, sY, sWidth, sHeight = lastConLine[2:6]

        return connectList




if __name__=='__main__':
    # 1.从原始数据提取出单个顾客的轨迹，用一个单独的txt存储
    allTrack = {}
    # allTrack["camera1"] = u"F:\项目实施部工作文件夹\上汽项目\\10.10人脸标签\\track_match_1010_cam1.csv"
    allTrack["camera2"] = u"F:\项目实施部工作文件夹\上汽项目\\10.10人脸标签\\track_match_1011_cam2.csv"
    allTrack["camera3"] = u"F:\项目实施部工作文件夹\上汽项目\\10.10人脸标签\\track_match_1011_cam3.csv"

    tracksPath = {}
    # tracksPath["camera1"] = u"F:\\项目实施部工作文件夹\\上汽项目\\10.10人脸标签\\1\\"
    tracksPath["camera2"] = u"F:\\项目实施部工作文件夹\\上汽项目\\10.10人脸标签\\2\\"
    tracksPath["camera3"] = u"F:\\项目实施部工作文件夹\\上汽项目\\10.10人脸标签\\3\\"

    dc = DataCleaning(tracksPath)
    allIdMap = {}
    allRealMap = {}
    for camerakey in allTrack:
        tempRealId, tempIdMap, startInShop,startTime,sale,data = dc.consumerTrack(allTrack[camerakey], tracksPath[camerakey])
        allIdMap[camerakey] = tempIdMap
        allRealMap[camerakey] = tempRealId

    print  allIdMap["camera2"]
    ct=ConnectTrack(u"F:\项目实施部工作文件夹\上汽项目\9.27新数据\\track\ch02\\tracks\\",allIdMap["camera2"])
    conList=ct.connect("289")#针对单个摄像头
    print conList